package com.example.bbgds.test.home.widget;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

/**
 * Created by zjzhu on 2016/4/26.
 */
public class WidgetListAdapter extends RecyclerView.Adapter<ItemViewHolder> implements View.OnClickListener {

    private Context mContext;
    private List<ItemInfo> mAppList;
    private OnItemClickListener mOnItemClickListener;

    public WidgetListAdapter(Context context) {
        mContext = context;
    }

    public void setAppList(List<ItemInfo> list) {
        mAppList = list;
        notifyDataSetChanged();
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        mOnItemClickListener = listener;
    }

    @Override
    public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case ItemInfo.VIEWTYPE_APP:
                return AppItemViewHolder.buildViewHolder(mContext);
            case ItemInfo.VIEWTYPE_MAIN:
                return MainWidgetHolder.buildViewHolder(mContext);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(ItemViewHolder holder, int position) {
        RecyclerView.LayoutParams lp = (RecyclerView.LayoutParams) holder.itemView.getLayoutParams();
        lp.leftMargin = 4;
        holder.bindData(mAppList.get(position), position);
        holder.itemView.setTag(position);
        holder.itemView.setOnClickListener(this);
    }

    @Override
    public int getItemCount() {
        return mAppList != null ? mAppList.size() : 0;
    }

    @Override
    public int getItemViewType(int position) {
        return mAppList != null ? mAppList.get(position).mViewType : super.getItemViewType(position);
    }

    @Override
    public void onClick(View v) {
        if (mOnItemClickListener != null) {
            int position = (Integer) v.getTag();
            mOnItemClickListener.onItemClick(mAppList.get(position), position);
        }
    }

    public interface OnItemClickListener {
        public void onItemClick(ItemInfo info, int position);
    }
}
